<script lang="ts">
  import { Modal } from "@skeletonlabs/skeleton-svelte";
  import { X } from "lucide-svelte";
  import { getContext } from "svelte";
  import { userStore } from "$lib/stores/user.svelte";
  import { request } from "$lib/utils/request";
  import { logout } from "$lib/api/user";
  import { goto } from "$app/navigation";
  import type { Store as ToastStore } from "@zag-js/toast";

  const toast: ToastStore = getContext("toast");

  async function doLogout() {
    await request(
      logout({
        session_id: userStore.userSession,
      })
    );
    toast.create({
      title: "成功",
      description: "退出登录成功!",
      type: "success",
    });
    goto("/");

    userStore.userSession = "";
    userStore.userInfo = null;
    userStore.showLogoutModal = false;
  }
</script>

<Modal
  open={true}
  triggerBase="btn preset-tonal"
  contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl w-[500px]"
  backdropClasses="backdrop-blur-xs"
  backdropBase="backdrop-none"
  onOpenChange={(ev) => {
    if (!ev.open) {
      userStore.showLogoutModal = false;
    }
  }}
>
  {#snippet content()}
    <header class="flex justify-between">
      <h4 class="h4">退出登录</h4>
      <button
        type="button"
        class="btn preset-ghost-primary-500"
        onclick={() => (userStore.showLogoutModal = false)}
      >
        <X />
      </button>
    </header>
    <p>是否退出登录？</p>
    <footer class="flex justify-end gap-4">
      <button
        type="button"
        class="btn preset-tonal"
        onclick={() => (userStore.showLogoutModal = false)}>取消</button
      >
      <button
        type="button"
        class="btn preset-filled-error-900-100"
        onclick={() => doLogout()}>退出登录</button
      >
    </footer>
  {/snippet}
</Modal>
